import { Injectable } from "@angular/core";
import { Platform, ModalController } from '@ionic/angular';
import { Base64ToGallery } from '@ionic-native/base64-to-gallery/ngx';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { ExportAsService, ExportAsConfig } from 'ngx-export-as';
import { EventService } from "../../shared/service/event.service";
import { QQSDK, QQShareOptions } from '@ionic-native/qqsdk/ngx';
import { ShareFormModalComponent } from "src/app/coms/share-form-modal/share-form-modal.component";
import { HttpService } from "src/app/shared/service/http.service";
declare let Dingtalk: any;
declare let Wechat: any;
declare let EnterpriseWechat: any;
declare let Kwais: any;
declare let Douyin: any;
declare let $: any;
@Injectable({
  providedIn: "root",
})
// tslint:disable
export class ShareService {
  exportAsConfig: ExportAsConfig = {
    type: 'png',
    options: {
      useCORS: true,
    },
    elementId: 'html2canvas'
  };

  constructor(
    private exportAsService: ExportAsService,
    private platform: Platform,
    private httpService: HttpService,
    public eventService: EventService,
    private modalController: ModalController,
    public globalService: AppGlobalService,
    private base64ToGallery: Base64ToGallery,
    private modalCtrl: ModalController,
    private qq: QQSDK
  ) {

    try {
      this.exportAsConfig = {
        type: 'png',
        options: {
          useCORS: true,
        },
        elementId: 'html2canvas'
      };
    } catch (error) {
      console.log("msg----->error===" + JSON.stringify(error));
    }
  }

  getTime() {
    return this.globalService.getNowFormatDateYYYYMMDDHHMM();
  }
  copyUrl(str) {
    this.dismiss();
    this.globalService.copyString(str)
  }
  savePic() {
    const that = this;
    const element = document.getElementById('html2canvas');
    const targetElement = document.getElementById('transfer-bg').cloneNode(true);
    element.appendChild(targetElement);
    setTimeout(() => {
      const dom = element.querySelector('#transfer-bg').querySelectorAll('img');
      for (let i = 0; i < dom.length; i++) {
        dom[i].crossOrigin = 'anonymous';
      }
      this.exportAsService.get(this.exportAsConfig).subscribe(content => {
        that.download(content);
        element.removeChild(targetElement);
        that.modalController.dismiss();
      });
    }, 500);
  }
  posterSharing(item) {
    this.modalController.dismiss();
    const tmpSessionId = localStorage.getItem('sessionId');
    const pageParams = {
      pageId: item.link.target,
      params: item.link.params ? item.link.params : {},
      sessionId: tmpSessionId
    };
    this.globalService.goToForward(pageParams);
  }
  download(dataUrl) {
    if (localStorage.getItem('client') === 'BROWSER') {
      const myBlob = this.dataURLtoBlob(dataUrl);
      const myUrl = URL.createObjectURL(myBlob);
      this.downloadFile(myUrl, 'deatil');
    } else {
      this.base64ToGallery.base64ToGallery(dataUrl, { prefix: '_img', mediaScanner: true }).then(
        (res) => {
          console.log('Saved image to gallery ', res);
          this.globalService.showToast('保存成功!', 1500, 'top');
        },
        err => console.log('Error saving image to gallery ', err)
      );
    }

  }
  dataURLtoBlob(dataurl) {
    const arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  downloadFile(url, name) {
    const a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    const clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
  }


  // 2024.04.23 新增分享到微信小程序
  shareWeiXinMiniApp(title?, content?, imageUrl?, webpageUrl?, wechatMiniProgrameId?, submit?) {
    try {
      const path = 'pages/index/index?shareUrl=' + encodeURIComponent(webpageUrl);

      let wechatUserName = wechatMiniProgrameId ? wechatMiniProgrameId : this.globalService.fengwoWechatMiniProgrameId;
      const params = {
        message: {
          title,
          description: content,
          thumb: imageUrl,
          media: {
            type: Wechat.Type.MINI, // 小程序
            webpageUrl,
            path,
            userName: wechatUserName, // 小程序原始id 默认蜂喔小程序          
            hdImageData: imageUrl, // 程序新版本的预览图二进制数据 不超过128kb 支持 地址 base64 temp
            withShareTicket: true, // 是否使用带shareTicket的分享
            miniprogramType: Wechat.Mini.RELEASE
          }

        }, scene: Wechat.Scene.SESSION     // TIMELINE朋友圈  SESSION会话   FAVORITE 收藏 默认朋友圈
      }
      console.log('share min params:' + JSON.stringify(params));
      Wechat.share(params, () => {
        console.log('success');
        if (submit) {
          this.shareSuccessSubmit(submit);
        }
      }, (reason) => {
        console.log('Wechat.share reason----->' + JSON.stringify(reason));
      });
    } catch (error) {
      console.log('Wechat.share error----->' + JSON.stringify(error));
    } finally {
      this.dismiss();
    }
  }


  shareSuccessSubmit(data) {
    const params1 = {
      id: data.id,
      content: data.content,
      sessionId: localStorage.getItem('sessionId')
    };
    this.httpService.post("application/submit", params1, res1 => {
      // this.appGlobalService.consoleLog('submit', res1);
      // console.log('submit after share thirdpart', res1);
      if (!data.content.disableShowToast && res1 && res1.message) {
        this.globalService.showToast(res1.message, 1500, 'middle');
      }
    });
  }


  // 分享到微信会话
  shareWeiXin(title?, content?, imageUrl?, webpageUrl?, submit?) {
    try {
      Wechat.share({
        message: {
          title,
          description: content,
          thumb: imageUrl,
          media: {
            type: Wechat.Type.WEBPAGE,
            webpageUrl
          }
        }, scene: Wechat.Scene.SESSION     // TIMELINE朋友圈  SESSION会话   FAVORITE 收藏 默认朋友圈
      }, () => {
        if (submit) {
          this.shareSuccessSubmit(submit);
        }
        console.log('success');
      }, (reason) => {
        console.log('error----->' + JSON.stringify(reason));
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
    finally {
      this.dismiss();
    }
  }
  //  Type: {
  // TEXT:     1,
  // FILE:     2,
  // IMAGE:    3,
  // VIDEO:    4,
  // LINK:     5,
  // FORWARD:  6,
  // MINAPP:   7 }

  shareEnterpriseWechat(title?, content?, imageUrl?, webpageUrl?, type?, submit?) {
    try {
      this.dismiss();

      if (localStorage.getItem('platform') === 'ios') {  // ios
        EnterpriseWechat.share({
          message: {
            title,
            description: content,
            thumb: imageUrl,
            webpageUrl
          }, type
        }, () => {
          console.log('success');
          if (submit) {
            this.shareSuccessSubmit(submit);
          }
        }, (reason) => {
          console.log('error----->' + JSON.stringify(reason));
        });
      } else if (localStorage.getItem('platform') === 'android') { // android        
        // 2024.11.14 android Wechat sdk已经支持 直接分享到企业微信
        Wechat.share({
          message: {
            title,
            description: content,
            thumb: imageUrl,
            enterpriseWechat: true,
            media: {
              type: Wechat.Type.WEBPAGE,
              webpageUrl
            }
          }, scene: Wechat.Scene.SESSION     // TIMELINE朋友圈  SESSION会话   FAVORITE 收藏 默认朋友圈
        }, () => {
          console.log('success');
        }, (reason) => {
          // console.log('error----->' + JSON.stringify(reason));
          this.globalService.showToast(JSON.stringify(reason), 2000, "middle");
        });
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  shareWeiXinImage(title?, content?, imageUrl?, webpageUrl?, submit?) {
    try {
      this.dismiss();
      Wechat.share({
        message: {
          title,
          description: content,
          thumb: webpageUrl,
          media: {
            type: Wechat.Type.IMAGE,
            image: imageUrl
          }
        }, scene: Wechat.Scene.SESSION     // TIMELINE朋友圈  SESSION会话   FAVORITE 收藏 默认朋友圈
      }, () => {
        console.log('success');
        if (submit) {
          this.shareSuccessSubmit(submit);
        }
      }, (reason) => {
        console.log('error----->' + JSON.stringify(reason));
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  checkSubmit(link?, submit?) {
    try {
      this.dismiss();
      if (localStorage.getItem('loginStatus') !== 'true') {
        this.eventService.emit('openPage', JSON.stringify(link));
      } else {
        if (submit) {
          this.shareSuccessSubmit(submit);
        }
      }

    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  // 取消 -> 关闭弹框
  async dismiss() {
    const modal = await this.modalController.getTop();
    if (modal) {
      this.modalController.dismiss({
        dismissed: true
      });
    }
  }
  shareMoments(title?, content?, imageUrl?, webpageUrl?, submit?) {
    try {
      this.dismiss();
      Wechat.share({
        message: {
          title,
          description: content,
          thumb: imageUrl,
          media: {
            type: Wechat.Type.WEBPAGE,
            webpageUrl
          }
        }, scene: Wechat.Scene.TIMELINE     // TIMELINE朋友圈  SESSION会话   FAVORITE 收藏 默认朋友圈
      }, () => {
        console.log('success');
        if (submit) {
          this.shareSuccessSubmit(submit);
        }
      }, (reason) => {
        // 分享到微信朋友圈校验
        console.log('error----->' + JSON.stringify(reason));
      });

    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  shareQQ(title?, content?, imageUrl?, webpageUrl?, submit?) {
    try {
      const that = this;
      const clientOptions: QQShareOptions = {
        client: this.qq.ClientType.QQ,
      };
      const shareNewsOptions: QQShareOptions = {
        client: this.qq.ClientType.QQ,
        title,
        scene: this.qq.Scene.QQ,
        url: encodeURI(webpageUrl),
        image: encodeURI(imageUrl),
        description: content
      };

      this.qq.checkClientInstalled(clientOptions)
        .then(() => {
          this.qq.shareNews(shareNewsOptions)
            .then(() => {
              console.log('shareText success');
              if (submit) {
                this.shareSuccessSubmit(submit);
              }
            })
            .catch(error => {
              console.log(error);
            });

        })
        .catch(() => {
          that.globalService.showToast('未安装QQ，请先下载QQ', 1500, 'middle');
        });
      this.dismiss();
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  shareQQImage(title?, content?, imageUrl?, webpageUrl?, submit?) {
    try {
      const that = this;
      const shareNewsOptions: QQShareOptions = {
        client: this.qq.ClientType.QQ,
        title,
        scene: this.qq.Scene.QQ,
        image: imageUrl,
        description: content
      };
      const clientOptions: QQShareOptions = {
        client: this.qq.ClientType.QQ,
      };
      this.qq.checkClientInstalled(clientOptions)
        .then(() => {
          this.qq.shareImage(shareNewsOptions)
            .then(() => {
              console.log('shareText success');
              if (submit) {
                this.shareSuccessSubmit(submit);
              }
            })
            .catch(error => {
              console.log(error);
            });

        })
        .catch(() => {
          that.globalService.showToast('未安装QQ，请先下载QQ', 1500, 'middle');
        });
      this.dismiss();
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  shareQQZone(title?, content?, imageUrl?, webpageUrl?, submit?) {
    try {
      const that = this;
      const clientOptions: QQShareOptions = {
        client: this.qq.ClientType.QQ,
      };
      const shareNewsOptions: QQShareOptions = {
        client: this.qq.ClientType.QQ,
        title,
        scene: this.qq.Scene.QQZone,
        url: encodeURI(webpageUrl),
        image: encodeURI(imageUrl),
        description: content
      };
      this.qq.checkClientInstalled(clientOptions)
        .then(() => {
          this.qq.shareNews(shareNewsOptions)
            .then(() => {
              console.log('shareText success');
              if (submit) {
                this.shareSuccessSubmit(submit);
              }
            })
            .catch(error => {
              console.log(error);
            });
        })
        .catch(() => {
          that.globalService.showToast('未安装QQ，请先下载QQ', 1500, 'middle');
        });
      this.dismiss();
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  shareDingTalk(title?, content?, imageUrl?, webpageUrl?, submit?) {
    try {
      const msgObj = {
        title,
        pageURL: webpageUrl,
        thumbURL: imageUrl,
        messageDescription: content
      };
      Dingtalk.shareWebObject(() => {
        console.log('shareText success');
        if (submit) {
          this.shareSuccessSubmit(submit);
        }
      }, error => {
        console.log(error);
      }, msgObj);
      this.dismiss();
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  async share58(obj) {
    try {
      if (obj && obj.fieldLinkType) {
        const param = {
          pageId: obj.fieldLinkType.link.target,
          params: obj.fieldLinkType.link.params,
          sessionId: localStorage.getItem('sessionId')
        };
        this.httpService.post('application/page', param, async res => {
          const view = JSON.parse(res.script).views[0];
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: 'recommend-modal',
            component: ShareFormModalComponent,
            componentProps: { tagData: view }
          });
          await modal.present();
          const modalData = await modal.onDidDismiss();
        });
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  shareDouyin(title?, content?, imageUrls?, webpageUrl?, shareType?, submit?) {
    if (imageUrls.length <= 0) {
      this.globalService.showToast('请选有图片的商机分享到抖音', 1500, 'middle');
      return;
    }
    const that = this;
    try {
      Douyin.isInstalled(
        (installed) => {
          console.log('installed----->' + JSON.stringify(installed));
          if (installed) {
            shareType = (shareType === undefined) ? 0 : shareType;
            Douyin.share({
              message: {
                title: title + content,
                description: content,
                imageUrls,
                webpageUrl
              }, shareType
            }, () => {
              if (submit) {
                this.shareSuccessSubmit(submit);
              }
            }, (reason) => {
              console.log('douyin share error----->' + JSON.stringify(reason));
            });
          } else {
            that.globalService.showToast('未安装抖音，请先下载抖音', 1500, 'middle');
          }
          that.dismiss();
        }, (reason) => {
          that.globalService.showToast('抖音未安装，请先下载抖音', 1500, 'middle');
          that.dismiss();
        });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  // 脚本配置 <dataItem name="isInValidImgPosterSharing" value="true"/>
  // 用于新增需求 求租求购，找店、找写字楼、找厂房等：没有图片或信息本身任何图片，生成画报，分享画报图片
  shareDouyinForInValidImg(item) {
    const modal = this.modalController.getTop();
    if (modal && modal['__zone_symbol__value'] !== undefined) {
      this.modalController.dismiss();
    }
    const tmpSessionId = localStorage.getItem('sessionId');
    const pageParams = {
      pageId: item.link.target,
      params: item.link.params ? item.link.params : {},
      sessionId: tmpSessionId
    };
    this.globalService.goToForward(pageParams);
  }
  shareKuaishou(title, content, imageUrl, webpageUrl, shareType, submit?) {
    let tmpShareType = 1; // 蜂喔商户1.6.22 新增分享类型 1 表示图片 2表示 视频
    if (shareType) {
      // tslint:disable-next-line:radix
      tmpShareType = parseInt(shareType);
    }
    try {
      const that = this;
      if (this.platform.is('ios')) {
        Kwais.isInstalled((installed) => {
          Kwais.share({
            message: {
              title,
              description: content,
              imageUrl,
              webpageUrl
            }, scene: tmpShareType
          }, () => {
            if (submit) {
              this.shareSuccessSubmit(submit);
            }
            console.log('success');
          }, (reason) => {
            console.log('error----->' + JSON.stringify(reason));
          });
          that.dismiss();
        }, (reason) => {
          that.globalService.showToast('未安装快手，请先下载快手', 1500, 'middle');
        });
      } else {
        Kwais.isInstalled(function (installed) {
          if (installed === 1) {
            console.log('kwais installed');
            // 已经安装快手 登陆状态校验
            const scope = "user_info";
            Kwais.auth(scope, (success) => {
              Kwais.share({
                message: {
                  title,
                  description: content,
                  imageUrl,
                  webpageUrl
                }, shareType: tmpShareType
              }, () => {
                if (submit) {
                  this.shareSuccessSubmit(submit);
                }
                console.log('success');
              }, (reason) => {
                console.log('error----->' + JSON.stringify(reason));
              });
            }, (error) => {
              // that.gloadService.showToast('未登录快手，请登陆', 1500, 'middle');
            });
          } else {
            that.globalService.showToast('未安装快手，请先下载快手', 1500, 'middle');
          }

          that.dismiss();
        }, function (reason) {
          // that.gloadService.showToast('未安装快手，请先下载快手', 1500, 'middle');
        });
      }

    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }


  // 2.1.0 蜂喔用户微信授权然后跳转自动登录
  async gotoAutoLoginWithWechatOpenId(clientType, callBackFunction: Function) {


    let that = this;
    const scope = "snsapi_userinfo";
    const state = "_" + new Date();
    // {"code":"031w3a100dAnLP13Xz000nWO3f3w3a1k","state":"_1681290561303","country":"","lang":"zh_CN"}
    // { errcode: "200",errmsg: "获取成功",access_token: null,unionid: null,openid: "ouq6d6l4MTcRaiQgFTSQBl_hdHAw",isLogin: true,nickname: "蜂喔 ",mobile: "17328795049",user_id: "643916890bbefd653bc9486c",skip: null, target: null,position: {code: "4403", name: "深圳"};

    if (typeof (Wechat) !== undefined) {
      let successLoginTarget = 0;
      let unSuccessLoginTarget = 0;
      if (window['wxlinkButton'] && window['wxlinkButton'].params && window['wxlinkButton'].params.page_name !== undefined) {
        // 设置登录不成功
        successLoginTarget = window['wxlinkButton'].params.page_name;
      }
      if (window['wxlinkButton'] && window['wxlinkButton'].target !== undefined) {
        // 设置登录失败
        unSuccessLoginTarget = window['wxlinkButton'].target;
      }

      Wechat.auth(scope, state, (response) => {
        const resObj = response;
        if (resObj['code']) {
          // type 1用户  2商户
          let type = 1;
          if (clientType) {
            type = clientType;
          }
          const authPath = '/wx/getAccessToken?type=' + type + '&code=' + resObj['code']
            + '&sessionid=' + localStorage.getItem('sessionId') + '&target=' + successLoginTarget + '&target2=' + unSuccessLoginTarget;
          this.httpService.get(authPath, async res => {
            if (res.isLogin) {
              that.globalService.loginRes.data.user_id = res.user_id;
              that.globalService.loginRes.data.position = res.position;
              that.globalService.loginRes.data.account = res.mobile;
              that.globalService.loginRes.params.position = res.position;
              that.globalService.loginRes.params.account = res.mobile;
              that.globalService.loginRes.params.user_id = res.user_id;
              that.globalService.loginRes.target = res.target; // 登录成功之后跳转的页面
            }
            if (res.openid !== null) {
              localStorage.setItem("wxloginOpenID", res.openid);
              try {
                console.log('dismiss wechat auth page done!');
                const modal = that.modalCtrl.getTop();
                if (modal) {
                  (await modal).dismiss('success');
                }
              } catch (error) {
                console.log('error', error)
              }
            }
            callBackFunction({ data: res, type: 1, isLogin: res.isLogin }); // type 1 表示请求成功
          });
        } else {
          callBackFunction({ data: null, type: 0 }); // type 0 表示请求异常 
          console.log('code is not find', resObj);
        }
      }, (reason) => {
        callBackFunction({ data: null, type: 0 });
        console.log('error:', reason);
      });
    } else {
      console.log('typeof (Wechat) === undefined', 'ok');
      callBackFunction({ data: null, type: 0 });
    }
  }
}
